<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb :breadcrumbInfo="breadcrumbInfo"></Breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert
        title="注意:只允许为第三个等级分类设置相关参数!"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类 -->
      <el-row class="goods-row">
        <el-col>
          <!-- 选择商品分类搜索框 -->
          <span class="span-info"> 选择商品分类: </span>
          <!-- 选择商品分类级联选择框 -->
          <el-cascader
            v-model="cascaderInfo.cascaderkeys"
            :options="CateList"
            :props="cascaderInfo.props"
            @change="handleCascaderChange"
            clearable
          ></el-cascader>

          <!-- Tabs标签页 -->
          <el-tabs v-model="tabsInfo.activeName" @tab-click="handleTabClick">
            <!-- 动态参数部分 -->
            <el-tab-pane label="动态参数" name="many" :disabled="isBtnDisable"
              ><el-button
                class="my-btn"
                type="primary"
                size="mini"
                :disabled="isBtnDisable"
                @click="addParamsDiaologInfo.isShow = true"
                >添加参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="tabsInfo.manyDate" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <!-- 循环渲染的Tag标签 -->
                    <el-tag
                      closable
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      @close="handleClose(index, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 动态添加的Tag -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInputRef"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <!-- 参数名称列 -->
                <el-table-column
                  label="参数名称"
                  prop="attr_name"
                ></el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="getEditParams(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParamsList(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 静态属性部分 -->
            <el-tab-pane label="静态属性" name="only" :disabled="isBtnDisable"
              ><el-button
                class="my-btn"
                type="primary"
                size="mini"
                :disabled="isBtnDisable"
                @click="addParamsDiaologInfo.isShow = true"
                >添加属性</el-button
              >
              <!-- 静态属性表格 -->
              <el-table :data="tabsInfo.onlyDate" border stripe>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      closable
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      @close="handleClose(index, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 动态添加的Tag -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInputRef"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                  label="参数名称"
                  prop="attr_name"
                ></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="getEditParams(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParamsList(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table></el-tab-pane
            >
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 编辑的对话框 -->
    <el-dialog
      title="商品分类编辑"
      :visible.sync="EditParamsDiaologInfo.isShow"
      width="50%"
    >
      <!-- 编辑参数表单 -->
      <el-form :model="EditParamsDiaologInfo" label-width="80px">
        <el-form-item label="参数名称">
          <el-input
            v-model="EditParamsDiaologInfo.attrInfo.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditParamsDiaologInfo.isShow = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="upEditParamsList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加操作对话框 -->
    <el-dialog
      :title="titleText"
      :visible.sync="addParamsDiaologInfo.isShow"
      width="50%"
      @close="AdddialogListClosed"
    >
      <!-- 添加参数操作表单 -->
      <el-form :model="addParamsDiaologInfo" label-width="80px">
        <el-form-item :label="labelText">
          <el-input
            v-model="addParamsDiaologInfo.addParams.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDiaologInfo.isShow = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="AddParamsList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../../components/Breadcrumb.vue";
export default {
  name: "Params",
  components: { Breadcrumb },

  data() {
    return {
      // 商品类别面包屑导航信息
      breadcrumbInfo: {
        titlePath: [
          { title: "首页", Path: "/Home" },
          { title: "商品管理", Path: "" },
          { title: "参数列表", Path: "" },
        ],
      },

      //  分类参数数据列表
      CateList: [],

      // 级联选择框配置信息
      cascaderInfo: {
        // 级联选择框双向绑定得到的数组
        cascaderkeys: [],
        props: {
          value: "cat_id",
          label: "cat_name",
          expandTrigger: "hover",
          children: "children",
        },
      },

      //Tabs标签页被激活的名称
      tabsInfo: {
        activeName: "many",
        // 静态属性信息
        onlyDate: [],
        // 动态参数信息
        manyDate: [],
      },

      // 编辑商品分类的Diaolog信息
      EditParamsDiaologInfo: {
        isShow: false,
        attrInfo: {},
      },
      // 添加参数的Diaolog信息
      addParamsDiaologInfo: {
        isShow: false,
        cat_id: 0,
        // 要提交的参数
        addParams: {
          attr_name: "",
          attr_sel: "",
          attr_vals: "",
        },
      },

      //控制文本框与按钮的切换显示
      inputVisible: false,
      // 文本框输入的内容
      inputValue: "",
    };
  },

  methods: {
    // 获取分类参数数据列表
    async getParamsList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数数据列表失败!");
      }
      this.CateList = res.data;
    },
    //监听CascaderChange时会触发判断
    handleCascaderChange() {
      //证明选择的不是三级分类
      if (this.cascaderInfo.cascaderkeys.length !== 3) {
        //  清空表格内容
        this.cascaderInfo.cascaderkeys = [];
        this.tabsInfo.onlyDate = [];
        this.tabsInfo.manyDate = [];
        return this.$message.error("选择的不是三级分类!");
      }
      //获取参数列表
      this.getCateList();
    },
    //  获取参数列表数据
    getCateList() {
      this.$http
        .get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.tabsInfo.activeName,
          },
        })
        .then((result) => {
          if (result.data.meta.status !== 200) {
            return this.$message.error(result.data.meta.msg);
          }
          // console.log(result.data.data);
          //拆分为数组
          result.data.data.forEach((item) => {
            // 为空就返回空白数组,不为空就分割
            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
            // 控制tag文本框的显示和隐藏
            item.inputVisible = false;
            // 控制tag文本框的内容
            item.inputValue = "";
          });

          if (this.tabsInfo.activeName === "only") {
            this.tabsInfo.onlyDate = result.data.data;
          } else {
            this.tabsInfo.manyDate = result.data.data;
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //Tab页签被点击的处理函数
    handleTabClick() {
      //获取参数列表
      this.getCateList();
    },
    // 获取要修改的参数列
    getEditParams(parList) {
      this.$http
        .get(`categories/${this.cateId}/attributes/${parList.attr_id}`, {
          attr_sel: "noly",
        })
        .then((result) => {
          this.EditParamsDiaologInfo.attrInfo = result.data.data;
          this.EditParamsDiaologInfo.isShow = true;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 更新参数列表并提交参数到服务器
    upEditParamsList() {
      this.$http
        .put(
          `categories/${this.EditParamsDiaologInfo.attrInfo.cat_id}/attributes/${this.EditParamsDiaologInfo.attrInfo.attr_id}`,
          {
            attr_name: this.EditParamsDiaologInfo.attrInfo.attr_name,
            attr_sel: this.EditParamsDiaologInfo.attrInfo.attr_sel,
            attr_vals: this.EditParamsDiaologInfo.attrInfo.attr_vals,
          }
        )
        .then((result) => {
          this.getCateList();
          this.$message.success(result.data.meta.msg);
          this.EditParamsDiaologInfo.isShow = false;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    // 删除操作
    deleteParamsList(parList) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.$http
            .delete(
              `categories/${parList.cat_id}/attributes/${parList.attr_id}`
            )
            .then(() => {
              this.getCateList();
            })
            .catch((err) => {
              this.$message.error(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 添加参数列表并提交参数到服务器
    AddParamsList() {
      this.addParamsDiaologInfo.addParams.attr_sel = this.tabsInfo.activeName;
      this.$http
        .post(
          `categories/${this.cateId}/attributes`,
          this.addParamsDiaologInfo.addParams
        )
        .then((result) => {
          if (result.data.meta.status !== 201) {
            return this.$message.error(result.data.meta.msg);
          }
          this.getCateList();
          this.addParamsDiaologInfo.isShow = false;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    // 监听对话框的关闭
    AdddialogListClosed() {
      // 清空表单
      this.addParamsDiaologInfo.addParams.attr_name = "";
    },
    //文本框失去焦点，或摁下了 Enter都会触发

    async handleInputConfirm(row) {
      // 如果输入为空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 输入合法
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // 发起请求保存到数据库
      this.saveAttrVals(row);
    },
    async saveAttrVals(row) {
      // 发起请求保存操作
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数失败!");
      }
      this.$message.success("修改参数成功!");
    },
    // 点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true;
      // 文本框自动获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInputRef.$refs.input.focus();
      });
    },
    // 监听tag标签的关闭
    handleClose(index, row) {
      // 删除对应参数可选项
      row.attr_vals.splice(index, 1);
      //发送服务器保存
      this.saveAttrVals(row);
    },
  },

  computed: {
    //如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisable() {
      if (this.cascaderInfo.cascaderkeys.length === 3) {
        return false;
      }
      return true;
    },
    //获取三级分类的id
    cateId() {
      // 选择的是三级分类
      if (this.cascaderInfo.cascaderkeys.length === 3) {
        return this.cascaderInfo.cascaderkeys[2];
      }
      return null;
    },
    //Dialog标题
    titleText() {
      if (this.tabsInfo.activeName === "many") {
        return "添加动态参数";
      } else {
        return "添加静态属性";
      }
    },

    labelText() {
      if (this.tabsInfo.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },

  created() {
    this.getParamsList();
  },
};
</script>

<style lang="less" scoped>
.goods-row {
  margin-top: 10px;
}
.span-info {
  font-size: 20px;
  margin-left: 5px;
}
.my-btn {
  margin-bottom: 15px;
}
.input-new-tag {
  width: 150px;
}
.button-new-tag,
.el-tag {
  margin-left: 20px;
}
</style>